import logging
from typing import Optional

import requests


class Telegraph:
    API_BASE_URL = 'https://api.telegra.ph'
    ACCESS_TOKEN = ''

    def __init__(self):
        with open('.telegraph-token', 'r') as f:
            self.ACCESS_TOKEN = f.readline().strip(' \n')
        logging.debug('Token:', self.ACCESS_TOKEN)

    def _convert_to_nodes(self, urls: list) -> bytes:
        import json
        data = [{'tag': 'img', 'attrs': {'src': url}} for url in urls]
        data = json.dumps(data).replace(' ', '').encode('utf-8')
        logging.debug(data)
        return data

    def _create_page(self, data: dict) -> Optional[str]:
        nodes = self._convert_to_nodes(data['pictures'])
        with requests.Session() as session:
            adapter = requests.adapters.HTTPAdapter(max_retries=10)
            session.mount('https://', adapter)
            resp = session.post(
                f'{self.API_BASE_URL}/createPage',
                timeout=5,
                data={
                    'access_token': self.ACCESS_TOKEN,
                    'title': data['title'].encode('utf-8'),
                    'author_name': data['url'],
                    'content':  nodes,
                }
            )
            logging.debug(resp.status_code)
            logging.debug(resp.content)

            resp_data = resp.json()
            if resp.ok and resp_data['ok']:
                logging.debug(resp_data['result'])
                return resp_data['result']['url']
            else:
                logging.warning(resp.status_code, resp.content)
                return None

    def push_album(self, pictures, title, url):
        logging.debug(pictures, title, url)
        try:
            return self._create_page({
                'title': title,
                'url': url,
                'pictures': pictures
            })
        except (requests.exceptions.ConnectionError, requests.exceptions.ReadTimeout) as e:
            logging.warning("Site not available:", e)
            return None
